class Solution3 {
    public ListNode detectCycle(ListNode head) {
       /*if (head==null){
            return null;
        }

        ListNode slow=head;
        ListNode fast=head.next;

        while(fast!=slow){
            if(fast.next==null||fast.next.next==null){
                return null;
            }
            slow=slow.next;
            fast=fast.next.next;
        }

        ListNode cur=head;
        while(cur!=slow){
            cur=cur.next;
            slow=slow.next;
        }
        return cur;*/

        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast != null) {
            slow = slow.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }
            if (fast == slow) {
                ListNode ptr = head;
                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }
                return ptr;
            }
        }
        return null;
    }
}

public class Text5 {
}
